import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    cachedViews: [],
    visitedViews: [
        {
          fullPath: "/dashboard",
          name: "Dashboard",
          path: "/dashboard",
          title: "首页",
          meta: {
            title: "首页",
            affix: true,
          },
        },
        {
          fullPath: "/documentation/documentation",
          name: "Documentation",
          path: "/documentation",
          title: "文档",
          meta: {
            title: "文档",
            affix: true,
          },
        }
      ],
  }
}
const state = getDefaultState()

const mutations = {
  ADD_VISITED_VIEW:(state,view)=>{
    
    // 判断数组内是否已经存在当前路由
    if(state.visitedViews.some(v=> v.fullPath == view.path)) return
    // 当前数组内没有的话将数据push到数组内
    state.visitedViews.push(
      Object.assign({},view,{
        title:view.meta.title || "no-name"
      })
    )
  },
  ADD_CACHED_VIEW:(state,view)=>{
    if(state.cachedViews.some(v=>v.name == view.name)) return
    state.cachedViews.push(view.name)
  },

  // 删除
  DEL_VISITED_VIEW:(state,view)=>{
    console.log('执行删除');
    // /迭代循环给每个属性创建一个可迭代对象，一致则裁剪
    for(const [i,v] of state.visitedViews.entries()){
      if(v.path === view.path){
        state.visitedViews.splice(i,1)
        break
      }
    }
  },
  /* DEL_CACHED_VIEW:(state,view)=>{
    // console.log('');
  } */
}

const actions = {
  // 添加
    addView({dispatch},view){
        // 触发的是两个函数，一个用于保存所有路由信息，一个用于保存缓存数据（只name）
        dispatch('addVisitedView',view)
        dispatch('addCachedView',view)
    },
    addVisitedView({commit},view){
      commit('ADD_VISITED_VIEW',view)
    },
    addCachedView({commit},view){
      commit('ADD_CACHED_VIEW', view)
    },

    // 删除
    delView({ dispatch, state }, view){
      // 返回一个promise用来做删除之后的后续操作,将更新之后的数据返回
      return new Promise(resolve=>{
        dispatch('delVisitedView',view)
      // dispatch('delCachedView',view)
        resolve({
          visitedViews:[...state.visitedViews]
        })
      })
      
    },
    delVisitedView({commit,state},view){
      return new Promise(resolve => {
      commit('DEL_VISITED_VIEW',view)
      resolve([...state.visitedViews])
      })
    },
    /* delCachedView({commit},view){
      commit('DEL_CACHED_VIEW',view)
    } */
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

